views:

48

answers:

4

Hi there,

Here is the query I am using:

SELECT k_id, COUNT(k_id) AS k_count 
FROM template_keyword_link 
WHERE k_id IN(1,2,3,4,5)
GROUP BY k_id;

This query returns something like
1 | 6
2 | 1
3 | 4
4 | 1
5 | 9

I want to add something like AND COUNT(k_id) = 1 so I end up with
2 | 1
4 | 1

However I get invalid use a group function.

How would I go about doing this?


Update:

Cheers guys,

The other part to my question is.

Can this be used as a delete statement?

something like

DELETE FROM 
template_keyword_link tkl
LEFT JOIN keywords k
ON tkl.k_id = k.k_id
WHERE tkl.k_id 
IN(SELECT k_id, COUNT(k_id) AS k_count 
FROM template_keyword_link 
WHERE k_id IN(1,2)
GROUP BY k_id
HAVING k_count = 1);

I get

You have an error in your SQL syntax;


So based on feedback i have altered this to use

DELETE tkl, k FROM 
template_keyword_link tkl
LEFT JOIN keywords k
ON tkl.k_id = k.k_id
WHERE tkl.k_id 
IN(SELECT k_id 
FROM template_keyword_link 
WHERE k_id IN(1,2)
GROUP BY k_id
HAVING COUNT(k_id) = 1);

However now I am getting

You can't specify target table 'tkl' for update in FROM clause

+4  A: 

WHERE clause is applied before the COUNT(*) has been calculated, so you need in HAVING, that is applied after.

  SELECT k_id,
         COUNT(k_id) AS k_count 
    FROM template_keyword_link 
   WHERE k_id IN (1, 2, 3, 4, 5)
GROUP BY k_id
  HAVING k_count = 1

See also: http://dev.mysql.com/doc/refman/5.1/en/select.html

** UPD **:

TIAS ;-) btw, the query syntactically seems fine for me, BUT did not you forget to specify template_keyword_link and keywords join condition clause? Does mysql give you any errors?

zerkms
This will become the accepted answer as soon as I can :)
Hailwood
Edited the query to include them ;)But as you can see, Im still getting an error.
Hailwood
because `IN` expects to get only one column, while you're giving 2. Move `count(*)` to `having`.
zerkms
I have updated the answer.
Hailwood
yes, you cannot select from the table you're modifying now :-S
zerkms
so that becomes a two part process :( ok thanks :)
Hailwood
+2  A: 

You're looking for the having clause which happens after grouping (the where clause is before grouping):

SELECT k_id, COUNT(k_id) AS k_count 
FROM template_keyword_link 
WHERE k_id IN(1,2,3,4,5)
GROUP BY k_id
HAVING COUNT(k_id) = 1;
paxdiablo
A: 

Nested subquery is a simple solution.

SELECT * FROM 
  (
    SELECT k_id, COUNT(k_id) AS k_count 
    FROM template_keyword_link 
    WHERE k_id IN(1,2,3,4,5)
    GROUP BY k_id 
  ) inner
WHERE inner.k_count = 1
burkestar
HAVING is simpler and more explicit.
Porculus
A: 

try this

SELECT k_id, COUNT(k_id) AS k_count 
FROM template_keyword_link 
WHERE k_id IN(1,2,3,4,5)
GROUP BY k_id
HAVING ( COUNT(k_id) = 1 )
JapanPro