从具有条件和来自另一个表的顺序的表中选择DISTINCT - PHP

时间:2017-12-10 19:00:52

标签: php mysqli

我有一个名为table_a的表:

|id |family   |gender   |stock
 1   bag       man       20
 2   bag       woman     23
 3   clothing  child     4
 4   shoe      man       0
 5   shoe      child     3
 6   bag       unissex   34
 7   bag       child     0

另一个名为table_b的表:

|id |gender
 1   man
 2   woman
 3   child
 4   unissex

我如何正确编码以下查询:SELECT DISTINCT gender FROM table_a WHERE family = 'bag' AND stock > '0' ORDER BY table_b.id ASC以便结果如下:[' man',' woman',' unissex&#39 ]。不管结果是什么,我希望得到的数组总是具有相同的顺序,' man'首先,'女人'在第二个等等,如果' man'那不是一个结果,而女人'来到第一,等等...

2 个答案:

答案 0 :(得分:0)

使用您当前的结构,您需要加入表格:

SELECT table_a.gender 
FROM table_a JOIN table_b ON table_a.gender=table_b.gender
WHERE table_a.family = 'bag' AND table_a.stock > 0 
GROUP BY table_a.gender
ORDER BY table_b.id

答案 1 :(得分:0)

使用 ORDER BY FIELD

指定订单
SELECT DISTINCT gender FROM table_a 
WHERE family = 'bag' AND stock > '0' 
 ORDER BY FIELD(gender,'man','woman','child', 'unissex')

它适用于MySQL