简体   繁体   中英

MySQL SELECT multiple rows with same column value based on value from another column

I am just getting started with MySQL queries, and have been fighting this for days with no luck finding a solution, so here goes.

Table structure as follows:

|         ID         |   TAG
| 111909684134416384 | WesternU
| 111909684134416384 | ldnon
| 111910470428008448 | ldnont
| 111910470428008448 | fb
| 111910605249712128 | LTC
| 111910605249712128 | ldnon
| 111911886139826176 | ldnont
| 111911886139826176 | WesternU

I would like to select, count, and list the TAG(s) where one TAG of the same ID has 'ldnont' or 'ldnon' listed.

Essentially, from this data set, I would like to list and count:

WesternU (2)
fb (1)
LTC (1)

I've been able to select and count, but only the first row of rows with duplicate ID. Thank-you in advance for any assistance.

 SELECT Tag, COUNT(*) FROM JodyTable 
      WHERE Tag NOT IN ('ldnon', 'ldnont')
         AND ID IN (SELECT ID FROM JodyTable WHERE Tag IN ('ldnon', 'ldnont'))

If i understand your question correctly - you want to count how many records with the same id has either "ldnon" or "ldnont" tags in table, not counting "ldnon" and "ldnont" themselves

select outer.tag, count(*) as outer.num
from table as outer
where outer.tag NOT = "ldnon" AND outer.tag NOT = "ldnont"  
outer.id IN (
select * from table  as inner
where outer.id = inner.id AND
(inner.tag = "ldnon" OR onner.tag="ldnont")
)
group by outer.tag
order by outer.num

this one is quite complicated maybe, but straightforward.

select  t1.tag, count(*)
from table as t1, table as t2 
where 
t1.id = t2.id AND t1.tag NOT = t2.tag AND 
t1.tag NOT = "ldnon" AND t1.tag NOT = "ldnont" AND
(t2.tag = "ldnon" OR t2.tag = "ldonont")
group by t1.tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM