连接table.A与table.B,table.B相对于table.A中的一个id有多行

时间:2016-02-08 06:43:12

标签: mysql sql

例如

select id,product from products;

id product
1  iPhone 6 
2  Dell Inspiron

pid是引用产品中产品ID的外键

select * from product_image;

id pid image
1  1   he7gu8h9d54w.jpg
2  2   jgeywfyu3r34.jpg
3  1   drtsw54e452r.jpg
4  2   weyr63tr236r.jpg

加入后,我得到了这个......

id product       img_id pid image
1  iPhone 6      1      1   he7gu8h9d54w.jpg
1  iPhone 6      3      1   drtsw54e452r.jpg
2  Dell Inspiron 2      2   jgeywfyu3r34.jpg
2  Dell Inspiron 4      1   drtsw54e452r.jpg

我从product_image获取了与产品表中的一个ID相关的多行 我想从product_image获得一行关于product_id ... plz help ..

我想要这个......

id product       img_id pid image
1  iPhone 6      1      1   he7gu8h9d54w.jpg
2  Dell Inspiron 4      1   drtsw54e452r.jpg

3 个答案:

答案 0 :(得分:2)

对于每种产品,您都可以使用NOT EXISTS确保不存在ID较低的图片:

select p.id, p.product, pi.id, pi.pid, pi.image
from products as p
  join product_image as pi on p.id = pi.pid
where not exists (select * from product_image as pi2
                  where pi2.pid = pi.pid
                    and pi2.id < pi.id)

或者,有一个子查询返回每个pid的最小ID,再次加入该子查询:

select p.id, p.product, pi.id, pi.pid, pi.image
from products as p
  join product_image as pi on p.id = pi.pid
  join (select pid, min(id) as id from product_image group by pid) pi2
      on pi.id = pi2.id and pi.pid = pi2.pid

可以在MySQL上执行得更快。

答案 1 :(得分:0)

您可以选择min(id)表单product_image来限制选择

select a.id, a.product, b.id, b.pid, b.image
from products as a, product_image as b
where a.id = b.pid
and b.id in (select min(id) from product_image group by pid)

答案 2 :(得分:0)

您所看到的是SELECT DISTiNCT ON的等价物,但MySQL中没有。请参阅此主题:Converting SELECT DISTINCT ON queries from Postgresql to MySQL

如果您不关心将返回哪一行,这将起作用:

SQL Fiddle

MySQL 5.6架构设置

CREATE TABLE prod
    (`id` int, `product` varchar(12))
;

INSERT INTO prod
    (`id`, `product`)
VALUES
    (1, 'iPhone6'),
    (2, 'DellInspiron')
;



CREATE TABLE img
    (`id` int, `pid` int, `image` varchar(16))
;

INSERT INTO img
    (`id`, `pid`, `image`)
VALUES
    (1, 1, 'he7gu8h9d54w.jpg'),
    (2, 2, 'jgeywfyu3r34.jpg'),
    (3, 1, 'drtsw54e452r.jpg'),
    (4, 2, 'weyr63tr236r.jpg')
;

查询1

select 
  id, pid, image 
from img
group by pid

<强> Results

| id | pid |            image |
|----|-----|------------------|
|  1 |   1 | he7gu8h9d54w.jpg |
|  2 |   2 | jgeywfyu3r34.jpg |

查询2

select 
  prod.id as prod_id, prod.product as prod_product
  , img.id as img_id, img.pid as img_pid, img.image as img_image 
from prod
join img on img.pid = prod.id
group by img.pid

<强> Results

| id |      product | id | pid |            image |
|----|--------------|----|-----|------------------|
|  1 |      iPhone6 |  1 |   1 | he7gu8h9d54w.jpg |
|  2 | DellInspiron |  2 |   2 | jgeywfyu3r34.jpg |