使用PHP和MySQL从多个表的多列中选择DISTINCT

Mar*_*cus 5 php mysql distinct

使用PHP和MySQL我试图从下面列出的所有4个表中的数字和类型列中获取所有不同的值:

table_1

ID|t1_number|t1_type
1|1|new
2|1|old
3|2|new
4|3|new
5|1|old

table_2

ID|t2_number|t2_type
1|1|future
2|1|new
3|3|past
4|3|new
5|1|new

table_3

ID|t3_number|t3_type
1|1|past
2|1|new
3|1|new
4|1|new
5|1|old

table_4

ID|t4_number|t4_type
1|1|new
2|4|new
3|3|old
4|2|new
5|1|new
Run Code Online (Sandbox Code Playgroud)

我想从上面的表中得到的值是:

数字:1,2,3,4

类型:新的,旧的,未来的,过去的

这是我到目前为止所拥有的; 但我不确定SQL是否正确或如何格式化while循环以获取值.

$sql = "SELECT DISTINCT table_1.t1_number, table_2.t2_number, table_3.t3_number, table_4.t4_number, table_1.t1_type, table_2.t2_type, table_3.t3_type, table_4.t4_type
FROM table_1 
JOIN table_2
JOIN table_3
JOIN table_4";

$result = @mysql_query($sql, $con) or die(mysql_error());

while($row = mysql_fetch_array($result)) {

    $numbers= $row[?????????];

}
Run Code Online (Sandbox Code Playgroud)

OMG*_*ies 4

如果一个列表比另一个列表具有更多值,则在单个查询中执行此操作可能会导致数字或类型列的输出中出现重复值。要获取任一列的不同值列表,这需要单独的查询:

数字

SELECT t1_number AS num
  FROM TABLE_1
UNION
SELECT t2_number
  FROM TABLE_2
UNION
SELECT t3_number
  FROM TABLE_3
UNION
SELECT t4_number
  FROM TABLE_4
Run Code Online (Sandbox Code Playgroud)

类型

SELECT t1_type AS type
  FROM TABLE_1
UNION
SELECT t2_type
  FROM TABLE_2
UNION
SELECT t3_type
  FROM TABLE_3
UNION
SELECT t4_type
  FROM TABLE_4
Run Code Online (Sandbox Code Playgroud)

在此 UNION 查询中运行 DISTINCT 没有任何价值,因为重复项将被删除,并且这只处理一列。