0

exp table: This is where I store entries while keeping the domains and sub domains in a separate table. The sub_domain column can have one or multiple ids that match the id column in misc.

+----+---------+-----------+------------+-----------+--------+-------------+------------+------------+
| id | user_id | job_type  | experience | exp_title | domain | sub_domain  | start      | end        |
+----+---------+-----------+------------+-----------+--------+-------------+------------+------------+
| 83 |     268 | Full Time | dasdfg     | dest      | 76     | 89,91,93,95 | 07/15/2012 | 07/31/2012 |
| 84 |     269 | Full Time | abcdef     | title     | 77     | 89          | 07/15/2011 | 07/31/2011 |
+----+---------+-----------+------------+-----------+--------+-------------+------------+------------+

misc table:

+-----+----------------------------------------+--------------+
| id  | name                                   | category     |
+-----+----------------------------------------+--------------+
|  89 | Name1                                   | category    |
|  91 | Name2                                   | category    |
|  93 | Name3                                   | category    |
|  95 | Name4                                   | category    |
|  55 | Name5                                   | category    |

I was wondering how to change LEFT JOIN misc c ON a.sub_domain=c.id if there are more than one sub_domains in the exp table while keeping in mind that there can be one id as well.

$query_str = "SELECT a.*, b.name, c.name AS sub_name
            FROM exp a 
            LEFT JOIN misc b ON a.domain=b.id
            LEFT JOIN misc c ON a.sub_domain=c.id
            WHERE a.user_id = ?";
4

3 に答える 3

0

これは2つのクエリで行う必要があります。主な理由の1つは、やりたいことをなんとか達成できたとしても、sub_name列を除いて実質的に同じデータを持つ行を返すことになるということです。それは本当に不要です。

最初JOINに2つのテーブルを作成してから、すべてのサブドメイン値に対してステートメントをa.domain = b.id使用する2番目のクエリを作成できます。IN(...)これは次のようになります。

$subdomains = explode(',', $data_from_first_query['sub_domain']);
if (count($subdomains)) {
  $q2 = '
    SELECT
      b.name
    FROM 
      misc AS b 
    WHERE b.id IN ('.implode(',',array_fill(0, count($subdomains), '?')).')';
}

次に、foreachを使用して、プレースホルダーの値をバインドします。

ただし、繰り返しになりますが、データベースが正規化されていることを確認することをお勧めします。

于 2012-07-20T10:33:21.370 に答える
0

これを試して

$query_str = 
    "SELECT a.*, b.name, c.name AS sub_name 
    FROM exp a  
    LEFT JOIN misc b ON a.domain=b.id 
    LEFT JOIN misc c ON locate(concat('','',c.id ,'',''),'','',a.sub_domain,'','') >0
    WHERE a.user_id = ?"; 
于 2012-07-20T10:21:46.167 に答える
0

コンマで区切られた値を持つ列を持つのは良くありません。質問の答えを読んでください:

コンマ区切りのリストをデータベースの列に保存するのは本当に悪いことですか?

簡単な答えは次のとおりです。それは本当に悪いことです。


FIND_IN_SET()設計を修正するまで、関数を使用できます。

$query_str = "
        SELECT a.*, b.name, c.name AS sub_name
        FROM exp a 
          LEFT JOIN misc b ON a.domain = b.id
          LEFT JOIN misc c ON FIND_IN_SET(c.id, a.sub_domain) 
         WHERE a.user_id = ?
             ";
于 2012-07-20T11:10:57.983 に答える