简体   繁体   English

将以下 MySQL 查询转换为 codeigniter

[英]convert following MySQL query into codeigniter

How to write this query in codeigniter如何在 codeigniter 中编写此查询

SELECT U.username,U.user_id
FROM storylikes S, user U
WHERE U.user_id=S.user_id_fk AND S.user_id_fk='$id'

try this :尝试这个 :

$this->db->select('u.username, u.user_id');
db->where('u. user_id = s.user_id_fk');
$this->db->where('s.user_id_fk = '.$id);
$query = $this->db->get('storylikes s, user u');

use $your_variable = $query->result();使用$your_variable = $query->result(); for the result为了结果

you should use joins instead of this query你应该使用连接而不是这个查询

$this->db->select('username,user_id');
$this->db->from('user');
$this->db->join('storylike','storylike.user_id_fk = user.user_id');
$this->db->where('storylike.user_id','$id');

as long as the db helper is loaded... You dont need to do anything special只要加载了 db helper ......你不需要做任何特别的事情

$query = $this->db->query('SELECT U.username,U.user_id FROM storylikes S, user U WHERE U.user_id=S.user_id_fk AND S.user_id_fk=$id);

Using a cartesian (cross join) by doing FROM with 2 tables can cause some unruly results if not used 'correctly'如果没有“正确”使用,通过对 2 个表执行 FROM 来使用笛卡尔(交叉连接)可能会导致一些不规则的结果

I suggest that if you are trying to just join tables together your SQL should be我建议,如果您只是尝试将表连接在一起,您的 SQL 应该是

SELECT U.username,U.user_id 
FROM storylikes S, user U 
INNER JOIN user U ON S.user_id = U.user_id_fk
WHERE S.user_id_fk=$id

CI querybuilder for this would be:用于此的 CI 查询构建器将是:

$query = $this->db->select('U.username,U.user_id')
    ->join('user U', 'S.user_id = U.user_id_fk', 'inner')
    ->where('S.user_id', $id)
    ->get('user U');

Using the correct join for the correct requirements is key;使用正确的连接来满足正确的要求是关键;

  1. INNER JOIN to ensure both FROM and the JOIN table match 1 for 1... INNER JOIN 以确保 FROM 和 JOIN 表匹配 1 for 1 ...
  2. LEFT JOIN if you want to ensure you have all data from your FROM table and any without results in the JOIN table show up as NULL LEFT JOIN 如果您想确保您拥有 FROM 表中的所有数据,而 JOIN 表中没有结果的任何数据都显示为 NULL
  3. RIGHT JOIN (opposite of left), to grab all data from the JOIN table and only matching data from the FROM table. RIGHT JOIN(左边的对面),从 JOIN 表中获取所有数据,并且只从 FROM 表中获取匹配的数据。
  4. CROSS (CARTESIAN) JOIN when you want to ... frankly... mash the data together... A CROSS JOIN will also function like an INNER JOIN when you stipulate criteria in the WHERE statement (like you did) but still, use the correct JOIN for the correct usage-case. CROSS (CARTESIAN) JOIN 当你想......坦率地说......将数据混合在一起......当你在 WHERE 语句中规定标准时,CROSS JOIN 也将像 INNER JOIN 一样起作用(就像你所做的那样)但是仍然使用正确使用案例的正确 JOIN。

There are other available joins but those are the basics.还有其他可用的连接,但这些是基础。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM