I have 4 tables in MySQL to join. Example
$select = $db->query("SELECT *
FROM ads
WHERE ad_pic='1'
AND ad_status = '1'
ORDER BY ad_id DESC LIMIT 0,4");
while ($fetch = $db->fetch($select)) {
$iquery = $db->query("SELECT *
FROM images
WHERE img_ads_id = '" . intval($fetch['ad_id']) . "'
AND img_status = '1'
LIMIT 1");
$thumb = $db->fetch($iquery);
$uselect = $db->query("SELECT *
FROM users
WHERE user_id = '".intval($fetch['ad_userid'])."'
AND user_status = '1'
LIMIT 1");
$ufetch = $db->fetch($uselect);
$cselect = $db->query("SELECT *
FROM category
WHERE cat_slug = '".safe_func($fetch['ad_category'])."'
LIMIT 1");
$cfetch = $db->fetch($cselect);
}
I want to know the way to join these in one select statement.
ads table
ad_id ad_userid ad_category
-------------------------------
1 2 5
images table
img_id img_ads_id
-------------------------------
1 1
users table
user_id user_name
-------------------------------
2 John
category table
cat_id cat_name
-------------------------------
5 Vehicles
SELECT *
FROM ads AS a
LEFT JOIN images AS i ON i.img_ads_id = a.ad_id AND i.img_status = 1
LEFT JOIN users AS u ON u.id = a.ad_userid AND u.user_status = 1
LEFT JOIN category AS c ON c.cat_slug = a.ad_category
WHERE a.ad_pic = 1
AND a.ad_status = 1
ORDER BY a.ad_id DESC
LIMIT 0,4
If an ad must have an image, user, or category, you may use a JOIN instead of a LEFT JOIN. If an ad can have more than one image, user, or category, you will need a more complex query.
Related
I have following 2 tables in mysql database :
1) products
p_id p_title p_price u_id
----------------------------------
1 tile 123 25
2 tile 133 24
3 tile 143 25
2) product_images
id img_name p_id u_id
1 name 1 25
2 name 1 25
3 name 2 24
I want to get all row from products table and only one row from product_images table. So to get this I am using following sql query but it's return all rows from product_images table. Should be one !
My Query :
$get_menu = mysqli_query($conn,
"SELECT DISTINCT products.p_title, products.p_price,
product_images.p_list_image, chef_profile.live_at, chef_profile.fname,
chef_profile.lname FROM products LEFT JOIN product_images ON products.p_id
= product_images.p_id LEFT JOIN chef_profile ON products.u_id =
chef_profile.u_id GROUP BY product_images.p_list_image") or die('sorry');
I am using this query in php while loop so that I want to show all unique data from products table and only one image from product_images table.
$num_menu = mysqli_num_rows($get_menu);
while( $get_result = mysqli_fetch_array($get_menu) ) {
/*echo '<pre>';
print_r($get_result);*/
$menu_title = htmlspecialchars($get_result['p_title']);
$menu_price = htmlspecialchars($get_result['p_price']);
$menu_image = htmlspecialchars($get_result['p_list_image']) ? htmlspecialchars($get_result['p_list_image']) : "no-menu-preview.png";
$live_at = htmlspecialchars($get_result['live_at']);
$fname = htmlspecialchars($get_result['fname']);
$lname = htmlspecialchars($get_result['lname']);
// echo..........data.. her...
}
There you have it.
You only have to group by p_id to get 1 result for each product.
SELECT DISTINCT products.p_title, products.p_price, product_images.p_list_image, chef_profile.live_at, chef_profile.fname, chef_profile.lname
FROM products
LEFT JOIN product_images ON products.p_id = product_images.p_id
LEFT JOIN chef_profile ON products.u_id = chef_profile.u_id
GROUP BY products.p_id
Hope it helps ;)
SELECT products.p_title,
products.p_price,
product_images.p_list_image,
chef_profile.live_at,
chef_profile.fname,
chef_profile.lname
FROM products
LEFT JOIN product_images ON products.p_id = product_images.p_id
LEFT JOIN chef_profile ON products.u_id = chef_profile.u_id
GROUP BY products.p_id,product_images.p_list_image
i need select some data from two tables ,
please help me use inner join for this selection .
players in selction2 must not be in selection1...
first select :
$rs = "SELECT *
FROM `player`
WHERE `status`=1 AND `credit`>=1 AND `username` NOT LIKE '$user'
ORDER BY ls ASC,credit DESC
LIMIT 0 ,10;
Second: this players must remove from result of selection1
$rs2 = "SELECT *
FROM `ip_log`
WHERE `playerid`='$ui' AND `win`='1' AND `date`='$date' ";`
You can use LEFT JOIN for this:
This shows the log messages for everyone not in selection 1.
SELECT l.*
FROM ip_log AS l
LEFT JOIN
(SELECT username
FROM player
WHERE status = 1 AND credit >= 1 AND username NOT LIKE '$user'
ORDER BY ls ASC, credit DESC
LIMIT 10) AS p
ON l.player = p.username
WHERE win = 1 and date = '$date'
AND p.username IS NULL
This shows the top 10 player data, except the ones with log messages in selection 2
SELECT p.*
FROM player AS p
LEFT JOIN ip_log AS l ON l.player = p.username AND l.win = 1 AND l.date = '$date'
WHERE p.status = 1 AND p.credit >= 1 AND p.username NOT LIKE '$user'
AND l.player IS NULL
ORDER BY p.ls ASC, p.credit DESC
LIMIT 10
In both cases, testing a column in the second table with IS NULL makes it return only the rows in the first table that don't have a match in the second table. See
Return row only if value doesn't exist
You can do it with LEFT JOIN
SELECT player.*,ip_log.* FROM `player` LEFT JOIN `ip_log` ON player.id!=ip_log.playerid GROUP BY player.id
i have three tables
Users :
id
username
password
Second table
Friends
id
myid
friends_id
and last one
CI_Sessions
session_id
User_id = default =0
User_data
i want Codeignier Query
select * from users where userid=$userid
select * from friends where myid=$userid or friend_id=$userid
select * from ci_sessions where user_id=$userid and user_data!=''
return result()
is possible to get all three in one statement ?
i was trying like this
function check_friends($username) {
$this->db->where('username',$username);
$q1 = $this->db->get('users');
$myid=$q1->row('userid');
if($username !='' ){
$this->db->select('*');
$this->db->from('users');// I use aliasing make joins easier
$this->db->where('userid',$myid);
$this->db->join('myfriends AS friends_tpl', 'friends_tpl.myid = '.$myid.' or friends_tpl.fid='.$myid.'', 'FULL');
$this->db->join('ci_sessions AS B', 'B.id_unite = A.userid', 'INNER');
$this->db->where('B.user_data !=','');
$this->db->where('B.id_unite !=','0');
$query = $this->db->get();
return $query->result();
}else{
}
}
Update
i try this query
$query = $this->db->query("select * from users as u inner join myfriends as f on f.fid = '".$this->session->userdata('userid')."' or f.myid= '".$this->session->userdata('userid')."' inner join ci_sessions as c on c.id_unite = u.userid where u.username != '$username' GROUP BY u.userid ");
but there is problem , this query not correct result as i want ,
this is friends table value
id | myid | friend_id
1 | 50 | 54
2 | 57 | 50
now if three users login , the query will show that user 54 is friend with user 57 i don't know w7y
Do like this
$query = $this->db->query( 'SELECT * -----
UNION ALL
SELECT * -----
UNION ALL
SELECT *---' );
this will give all result...
Hi as the title say i have a php code where i sucefully echo the articles in a table, the problem is in this table i just have cat_id the parent_id is referenced in other table..
"articulos" table
id | titulo | fecha_evento | descripcion | img | cat_id
"categoriablog" table
id | parent_id
This is the way im making my query
$query1 = "SELECT id,titulo,fecha_evento,descripcion,img FROM articulos WHERE cat_id = 1";
$result = mysql_query($query1);
My goal is to do something like this, but "parent_id" is in other table
$query1 = "SELECT id,titulo,fecha_evento,descripcion,img FROM articulos WHERE cat_id = 1 OR parent_id = 1";
$result = mysql_query($query1);
JOIN the two tables:
SELECT
a.id, a.titulo, a.fecha_evento, a.descripcion, a.img
FROM Article AS a
INNER JOIN Category AS c ON a.cat_id = c.id
WHERE a.cat_id = x
OR c.parent_id = x
You can use a sub query
SELECT id,titulo,fecha_evento,descripcion,img FROM Article
WHERE cat_id = 1 OR cat_id IN
(SELECT id from Category where parent_id=1)
Edit
Please note that this solution is a little bit slower than the JOIN solution in the answer by Mahmoud.
have a poll table which has 10 categories and I want to view the top 5 results from highest to lowest limit into 5 categories. How can I do this in php and mysql?
here are example tables
categories
id
category_name
Votes
id
category_id
user_id
Users
id
username
here is my sample query:
$q = mysql_query("SELECT * from categories");
while($data = mysql_fetch_array($q){
$votes = mysql_query("SELECT * from votes where category_id=".$data['id']."");
$data_vote = mysql_nuw_rows($votes);
echo $data['category_name']."has".$data_vote."Votes";
}
I want my output to be like this from the highest votes in a categories
category1 has 30 votes
category3 has 25 votes
category5 has 23 votes
category2 has 15 votes
category4 has 10 votes
Use:
$q = mysql_query("SELECT c.category_name,
COALESCE(COUNT(v.category_id), 0) AS cnt
FROM CATEGORIES c
LEFT JOIN VOTES v ON v.category_id = c.id
GROUP BY c.category_name
ORDER BY cnt DESC
LIMIT 5 ");
while($data = mysql_fetch_array($q) {
echo $data['category_name'] ." has ". $data['cnt'] ." votes"
}
That query should do it:
select c.category_name, count(v.id) as number_of_votes
from CATEGORIES c
left join VOTES v on v.category_id = c.id
group by c.id
order by number_of_votes desc
limit 5
(assuming your VOTES table primary key is "id"