Forum Moderators: coopster
If we have two columns that hold redundant data, such as an ItemID column and a colorID column:
A = itemID
B = colorID
+-------+
¦ A ¦ B ¦
+---+---+
¦ 1 ¦ 1 ¦
¦ 1 ¦ 1 ¦
¦ 1 ¦ 3 ¦
¦ 2 ¦ 1 ¦
¦ 2 ¦ 3 ¦
¦ 2 ¦ 3 ¦
¦ 2 ¦ 5 ¦
¦ 3 ¦ 5 ¦
+---+---+
I have tried something to the effect of:
SELECT itemID, colorID, count(colorID) from myTable GROUP BY colorID HAVING itemID = 1;
But, this returns skewed results.
Any help would be greatly appreciated.
SELECT DISTINCT(column1), COUNT(column2) FROM table GROUP BY column1;
but that query seems to give me the following results:
For ItemID 1, there exist 3 entries
For ItemID 2, there exist 4 entries
For ItemID 3, there exist 1 entry
That is close, but I need it filtered one step further.
ItemID 1 may have had 3 entires,
but I need to know that ItemID 1 had 2 entries with colorID = 1 and 1 entry with colorID = 3
SELECT DISTINCT(column1)
FROM table
GROUP BY column1
ORDER BY column1;
while(looping through that){
$itemid = column1
SELECT column2,
COUNT(column2)
FROM table
WHERE column1 = '$itemid'
GROUP BY column2
ORDER by column2
while(looping through that){
$color = column2
$count = the count
echo "For $itemid there exist $count entries with colorid $color<br>";
}// inner loop
}// outer loop
GROUP BYclause.
SELECT itemID, count(colorID), colorID FROM myTable GROUP BY itemID, colorID ORDER BY itemID, colorID;
Remember, when there is a
GROUP BYclause, there are certain rules that apply for grouping columns. One of those rules is "The Single-Value Rule" -- every column named in the
SELECTlist must also be a grouping column unless it is an argument for one of the set functions. MySQL extends standard SQL by allowing you to use columns or calculations in a
SELECTlist that don't appear in a
GROUP BYclause. However, we are warned not to use this feature unless the columns you omit from the
GROUP BYclause are not unique in the group because you will get unpredictable results.
Resource:
[dev.mysql.com...]
coopster, that worked perfectly! Thank you for your help and especially for the explanation. That was very helpful.
Thanks again to all!
BTW, I keep my socks in two different drawers:
SELECTBut, considering the efficiency you have shown, I am hereby changing my ways ;)
sock_drawer_1.sock AS leftfoot,
sock_drawer_2.sock AS rightfoot
FROM sock_drawer_1, sock_drawer_2
WHERE sock_drawer_1.sock = sock_drawer_2.sock
AND sock_drawer_1.sock_color = 'red'
;
$result = mysql_query
("
SELECT househould.item_location,
items.item_id,
COUNT(household.item_type)AS num_socks
FROM household, items
WHERE items.description LIKE '%sock%'
AND items.color = 'white'
AND items.stripes = 'no'
AND items.item_type = household.item_type
GROUP BY items.item_type, items.color
HAVING num_socks = '2'
LIMIT 0,1
");
$row = mysql_fetch_array($result);
$where_the_heck_some_socks_are = $row[0];
echo "$where_the_heck_some_socks_are";