3

Here is my table:

 page_id | string_id |       content
       1 |  terms_en | etc text lorem ipsum
       1 |  terms_es | etc espanol lorem    
       2 |   tabtext | stuff text lorem etc
       3 |  veh_name | etc stuff letters lala
       4 |   btn_txt | text for a button etc
       4 | alert_txt | text for an alert etc lala
       5 |  page_cnt | lala pagecontent etc lala

I need to select all of the page_ids where the page_id only has one string_id associated with it

In essence, I am trying to return the page_ids: 2, 3, and 5 from this table.

My SQL looks like this:

SELECT page_id, string_id
FROM lang_strings
WHERE string_id != 'content'
GROUP BY string_id, page_id
HAVING count(string_id) < 2 AND count(page_id) < 2;
4

5 に答える 5

3

You have to use count(distinct ...):

SELECT page_id, count(distinct string_id) 
FROM lang_strings
WHERE string_id != 'content'
GROUP BY page_id
HAVING count(distinct string_id) = 1

Using distinct within the count() handles the case where there's multiple rows with the same string_id, which of course would count as there being just one value (that occurs many times).

You haven't specified which database you're using, so you may likely find that you don't have to select count(distinct string_id) for the query to work

于 2013-03-07T01:48:45.330 に答える
1

これを試して:

SELECT page_id
     , max(string_id) as string_id
FROM lang_strings
WHERE string_id != 'content'
GROUP BY page_id
HAVING count(page_id) = 1

だけが必要な場合はpage_id、MAX関数を使用して2番目の列を削除できます。

于 2013-03-07T01:49:03.410 に答える
1

これはあなたのためにそれをするはずです。

SELECT page_id
FROM (
    SELECT DISTINCT
        page_id,
        string_id
    FROM lang_strings
) t1
GROUP BY t1.page_id
HAVING COUNT(page_id) = 1
于 2013-03-07T01:52:44.300 に答える
1

The problem with your query is that you are grouping by both page_id and string_id.

You can fix the problem by just grouping by page_id:

SELECT page_id, string_id
FROM lang_strings
WHERE string_id != 'content'
GROUP BY page_id
HAVING count(*) = 1

This returns the page_ids that have only one row. So, they have only one string id.

If you mean that string id takes on only one value, but there can be multiple rows, then I would recommend the following having clause:

where max(string_id) = min(string_id)

You can also use:

where count(distinct string_id) = 1

However, the max/min comparison usually performs better than the count(distinct).

于 2013-03-07T02:04:34.727 に答える
1

Try below code

SELECT page_id FROM lang_strings
GROUP BY page_id
HAVING count(string_id) = 1

As you have not specified in question i am not getting why you are using WHERE string_id != 'content'

于 2013-03-07T08:54:35.573 に答える