使用php我试图从2个不同的表中获取数据:
Table : products +-------+---------+----------+ | pcode | product | category | +-------+---------+----------+ | 1 | jeans | men | +-------+---------+----------+ | 2 | shirt | men | +-------+---------+----------+ Table : colors +-------+---------+ | pcode | colors | +-------+---------+ | 1 | blue | +-------+---------+ | 1 | black | +-------+---------+ | 1 | white | +-------+---------+ | 2 | yellow | +-------+---------+ Result I want should be like : +-------+---------+----------+---------------------+ | pcode | product | category | colors | +-------+---------+----------+---------------------+ | 1 | jeans | men | black, blue, white | +-------+---------+----------+---------------------+ | 2 | shirt | men | yellow | +-------+---------+----------+---------------------+
请指导我。
提前致谢。
维克拉姆
答案 0 :(得分:2)
SELECT p.pcode,product,category,GROUP_CONCAT(colors) as colors
FROM products p JOIN colors c
ON p.pcode=c.pcode
GROUP BY product
答案 1 :(得分:0)
Mihai的查询也在工作..
也可以尝试这个..
select p.*, group_concat(colors separator ',') colors from products p left outer join colors c on p.pcode=c.pcode group by p.pcode;
答案 2 :(得分:0)
注意:您可以尝试使用PDO或MySqli库(下面的链接)来运行此SQL语句
您可以尝试这个SQL语句我认为它会完成这项工作,但会以您要求的不同方式显示行,只需尝试一下:
SELECT colors.pcode , products.products ,products.category , colors.colors
FROM colors
INNER JOIN FIRST ON colors.pcode = products.pcode
结果:
或者如果你想要问你应该在多个SQL Satatement中分离工作:
SELECT colors FROM colors WHERE pcode = 1
使用一些SQL Sattement获得所有颜色
然后以这种方式获取产品和产品和分类:
SELECT product , category FROM products WHERE pcode = 1
还有一些像这样的你会得到你需要的所有东西
但我更喜欢第一个,因为它更方便,更快。
链接:
PDO:
http://php.net/manual/en/book.pdo.php
MYSQLI:
度过愉快的一天:)