MySQL选择帮助;子查询?

时间:2011-01-04 01:31:38

标签: mysql sql

我有两张桌子,我正在查询。在一张桌子中,有一些字段表示照片中的特色是死亡/活着,在名人堂等等。我刚刚添加的字段称为“new_flag”。这表示照片是否属于我的广告资源

没有GROUP BY,结果看起来像这样(注意一些玩家有多个产品/照片)

name            firstname  lastname     hall_of_fame  deceased  new_flag
----            ---------  --------     ------------  --------  --------
EARL AVERILL SR EARL       AVERILL SR   Y             Y         Y
BILL TERRY      BILL       TERRY        Y             Y         N
BILL TERRY      BILL       TERRY        Y             Y         Y
BILL TERRY      BILL       TERRY        Y             Y         N
BOBBY DOERR     BOBBY      DOERR        Y             N         N
BOBBY DOERR     BOBBY      DOERR        Y             N         N

使用GROUP BY我的查询看起来像这样,但它不能总是找到新标志,因为每个玩家可能有多个记录。

SELECT    CONCAT(a.firstname,' ',a.lastname) AS name,
          a.firstname,
          a.lastname,
          b.hall_of_fame,
          b.deceased,
          b.new_flag
 FROM     vm_product_name AS a,
          vm_product_new_attribute AS b  
 WHERE    b.hall_of_fame ='Y'
   AND    a.product_id = b.product_id
 GROUP BY CONCAT(a.firstname,' ',a.lastname)
 ORDER BY a.lastname,
          a.firstname;

问题在于我只希望每个玩家在我的网页上出现一次,但是.....我还想在玩家姓名旁边添加一个“新”图标,如果他们至少有一张新照片。我有什么想法可以做到这一点吗?

我知道这不是执行此操作的最佳方式,但它是作为Joomla / Virtumart扩展构建的,此时我无法更改数据库结构。

2 个答案:

答案 0 :(得分:4)

SELECT CONCAT(a.firstname, ' ', a.lastname) AS name, a.firstname, a.lastname,
    b.hall_of_fame, b.deceased, MAX(b.new_flag) AS new_flag
FROM vm_product_name AS a
    INNER JOIN vm_product_new_attribute AS b
        ON a.product_id = b.product_id
WHERE b.hall_of_fame = 'Y'
GROUP BY a.lastname, a.firstname
ORDER BY a.lastname, a.firstname

答案 1 :(得分:-1)

你可能想要一个左连接......

SELECT * FROM (
SELECT CONCAT(vm_product_name.firstname, ' ', vm_product_name.lastname) AS name
vm_product_name.firstname AS firstname, 
vm_product_name.lastname, AS lastname,
vm_product_new_attribute.hall_of_fame AS hall_of_fame,
vm_product_new_attribute.deceased AS deceased, 
vm_product_new_attribute.new_flag AS new_flag
FROM vm_product_name LEFT JOIN vm_product_new_attribute ON vm_product_name.product_id = vm_product_new_attribute.product_id 
ORDER BY lastname, firstname) AS MYRESULT GROUP BY CONCAT(lastname, ' ',firstname);