如何选择两个表mysql使用php

时间:2016-02-03 02:26:48

标签: php mysql

Ex:我有两张桌子: 表1:

 _________________________________
| userID | Key        | value     |
 ---------------------------------
| 2      | D of Birth | 20-07     |
| 2      | sex        | M         |
| 3      | D of Birth | 12-09     |
| 3      | sex        | FM        |
| 1      | D of Birth | 20-01     |
| 1      | sex        | M         |
 ---------------------------------

表2

Array 
  [0]
     [ID] = 1
     [name] = David
     [born] = 1987
     [D o Birth] = 20-01
     [sex] = M
  [1]
     [ID] = 2
     [name] = Michale
     [born] = 1998
     [D o Birth] = 20-07
     [sex] = M
  ...

如何选择并添加到数组:

{{1}}

我不知道他们为什么不简单地使用一张桌子?两个表是更快的查询? 非常感谢!

1 个答案:

答案 0 :(得分:0)

You need a crosstab. With a crosstab, rows can become columns and visa versa.

Unfortunately MySQL doesn't have a crosstab support. So you need to create a custom query:

SELECT user.*, dofbirth.value AS `D of Birth`, sex.value AS sex
  FROM user
    LEFT JOIN userprop AS dofbirth
      ON dofbirth.key = 'D of Birth' AND user.id = dofbirth.userID
    LEFT JOIN userprop AS sex
      ON sex.key = 'sex' AND user.id = `sex`.userID

You need to know the columns in advance, so you need to know the keys of the userprop table in advance.


You could get all the keys with the query

SELECT DISTINCT key FROM userprop

Than you need to loop though the keys in PHP and build up the crosstab query.

$result = $db->query("SELECT DISTINCT key FROM userprop");

$cols = ["user.*"];
$from = "user";

while (list($key) = $result->fetch_row()) {
  $table = strtolower(preg_replace('/\W/', $key));

  $cols[] = "{$table}.value AS `" . str_replace('`', '', $key) . "`";
  $from .= " LEFT JOIN userprop AS `{$table}` ON `{$table}`.key = \"" . $db->real_escape_string($key) . "\" AND `{$table}`.userID = user.id"; 
}

$query = "SELECT " . join(', ', $cols) . " FROM " . $from;
...