Querying comma separated field? - php

I am trying to output a select dropdown options based on a comma separated field where if the user has been assigned an ID of 1 and 2 for example then I want to output the locations id has 1 and 2:
Users table:
id (which equals 1) and usergrouplocid which is a text field with (1,2)
Location Table:
id which auto_increment and a loc_id see iamge below:
My query is as follows:
$query = "SELECT room_location.*, client_room.*, users.* FROM room_location INNER JOIN client_room ON room_location.user_loc_id = client_room.id INNER JOIN users ON room_location.user_loc_id = users.userGroupLocID WHERE 1 IN (userGroupLocID) ORDER BY room_location.location";
The query above works fine but it only outputs where the id of 1 exists in usergrouplocid, so how do I get the query to find if 1, 2, 3 or 4 etc is in the usergrouplocid.

Just in case you really need it sorted now without redesigning your database (which I would)...
$ids = array(1,2,4);
$query = "SELECT room_location.*, client_room.*, users.* FROM room_location INNER JOIN client_room ON room_location.user_loc_id = client_room.id INNER JOIN users ON room_location.user_loc_id = users.userGroupLocID WHERE userGroupLocID REGEXP '(^|,)(".implode('|',$ids).")(,|$)' ORDER BY room_location.location";

Related

joining 2 tables in msqli

table posts
table users
how would i count posts for specific user logged in. for example when user with id 3 is logged in it should show me 4 posts
I already did it for total posts count:
<?php
$post_query1 = "SELECT count(*) AS total FROM posts ";
$post_result1 = mysqli_query($db, $post_query1);
$post1 = mysqli_fetch_array($post_result1);
?>
Try below example :
select count(*) as total from user as u inner join post as p on p.id_user = u.id_user AND u.id_user = 3
If you want to get only the posts count for the particular user, say user with id = 3, your query should be this:
$query = "SELECT count(*) AS total FROM posts WHERE id_users = 3";
But if you want to get both the posts count as well as the user information and other post information, you will have to run a join query on both the users and posts table. Your query would now become:
$query = "SELECT u.*, p.*, count(p.id_posts) FROM users AS u JOIN posts AS p ON u.id_users = p.id_users WHERE p.id_users = 3";
Some Useful Notes
p.* - * is a wildcard character that means get all the columns in the posts table
u.* - * is a wildcard that means get all the columns in the users table
posts as p - AS is for aliasing. So, we are giving posts table a temporary name.
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
Note: It is necessary that you have to join two/more tables only with the help of foreign key. Without the foreign key is is meaningless to join two or more tables
Reference 1: https://www.w3schools.com/sql/sql_join.asp
Reference 2: https://www.tutorialspoint.com/mysql/mysql-using-joins.htm
As per the Question what you have asked to join the tables
Query:
SELECT * FROM TABLE 1 JOIN TABLE 2 ON TABLE1.id = TABLE2.id WHERE TABLE2.ID=3
Kindly replace TABLE1 & TABLE2 with the Tables that are to be joined and the id with the foreign key what you have specified in the Table.
Hope so this might be helpful for you to write your own code in future. Happy Coding :)
You have only to use a simple join.
SELECT count(*)
FROM USER u,
post p
WHERE p.id_user = u.id_user
AND u.id_user = 3

mySQL JOIN on one to many

I have multiple tables that are linked together on the search page. They are currently queried like this:
SELECT * FROM tripreportentries
JOIN tripreport ON tripreportentries.reportid = tripreport.tripreportid
JOIN user_details on tripreportentries.userid = user_details.userid
WHERE TripEntryHeading LIKE '%%' AND tripreportentries.ispublic = 1
ORDER BY tripreportentryid
I have since created a new table called tripphotos with the table columns named:
tripphotoid
reportid
entryid
photoname
The issue is each entry can have more than one corresponding photo in the photo table.
I am looking to find a way to JOIN the new table to the statement above but not return several rows for each entry id.
Any ideas on how to join this table?
EDIT - I also want to just tie one image to the returned row and not all of them just so I can show the image as a thumbnail on the browse page
I normally would list every column and group by the non aggregates, but mySQL will allow this I believe; given the mySQL group by extensions; and we expect the tripReport and user_Details columns to be the same for each joined photoname.
SELECT tripReport.*, user_details.*, max(photoname) as maxPhotoPerReport
FROM tripreportentries
JOIN tripreport ON tripreportentries.reportid = tripreport.tripreportid
JOIN user_details ON tripreportentries.userid = user_details.userid
JOIN tripphotos ON tripreportentries.reportid = tripPhotos.ReportID
WHERE TripEntryHeading LIKE '%%' AND tripreportentries.ispublic = 1
GROUP BY ReportId
ORDER BY tripreportentryid
or we could do this using an inline view to get the max photo for each report and then join that set to your base query.
SELECT *
FROM tripreportentries
JOIN tripreport ON tripreportentries.reportid = tripreport.tripreportid
JOIN user_details on tripreportentries.userid = user_details.userid
JOIN (SELECT max(photoName) as MaxPhotoPerReport, ReportID
FROM TripPhotos
GROUP BY ReportID) B
ON B.ReportID = tripReport.ReportId
WHERE TripEntryHeading LIKE '%%' AND tripreportentries.ispublic = 1
ORDER BY tripreportentryid

Pull MIN and MAX prices from database

I need to select all (*) the rows from table1, table2, table3.. but I need to select the MIN and MAX price from table 2 within this INNER JOIN. I've read up on how to do this, but how do I do this within an INNER JOIN, and how do I display it in a PHP variable.
Initial Problem: How do I display the min and max values once I pull them.. (e.g $Result['MinPrice'], $Result['MaxPrice']).
Here's my query:
$Query = mysql_query("
SELECT *
FROM table1
INNER JOIN table2 ON table1.UserID = table2.UserID
INNER JOIN tables3 ON table2.DeviceID = table3.DeviceID
WHERE table2.DeviceID = '$GetDeviceID'
");
Here is the tables structure:
table1 = usersinfo
UserID UserFirstName UserLastName UserDisplayName
1 John Doe John D.
table2 = listings
ListingID UserID DeviceID
11 1 2
table3 = devices
DeviceID
2
If you really want to do what you're asking in this way you can use the query that is displayed below. This does, however, return a lot of duplicate rows if you have multiple rows returned when querying. Try it and see if it works.
$Query = mysql_query("
SELECT table1.*, table2.*, table3.*,
MIN(table2.price) as minny,
MAX(table2.price) as maxxy
FROM table1
INNER JOIN table2 ON table1.UserID = table2.UserID
INNER JOIN tables3 ON table1.DeviceID = table3.DeviceID
WHERE table1.DeviceID = '$Something'
GROUP BY table2.ListingAskingPrice
");
Then get this value by doing $result['minny'] and $result['maxxy']

Mysql Join without replacing value of original id

I am trying to join my users table with another table using the following query...
SELECT * FROM (`activities`)
JOIN `users` ON `users`.`id` = `activities`.`user`
WHERE `user_subdomain` = 'hi' OR user_subdomain = ''
ORDER BY `activities`.`id` desc
LIMIT 10
Is there any way to do the join so that the id of the user does not replace the id of the activity?
For example, currently if there is an activity with the id of 10 and the user 2 the id will be replaced by the id of the users table and show as 2 after I run the query.
Thanks a lot for the help!
Whenever you are joining tables, you ought to be explicit about the columns you select rather than using SELECT *, and specify column aliases for them when the same column name is used in multiple tables.
SELECT
activities.id,
activities.othercol,
/* Alias to userid */
users.id AS userid,
users.name,
users.anothercolumn
FROM (`activities`)
JOIN `users` ON `users`.`id` = `activities`.`user`
WHERE `user_subdomain` = 'hi' OR user_subdomain = ''
ORDER BY `activities`.`id` desc
LIMIT 10
Though it isn't strictly necessary to prepend the table name to each, unless the column names are the same.
SELECT
activities.id AS activityid,
othercol,
users.id AS userid,
name,
anothercolumn

mysql joining two table

table user:
id_u* f_name l_name
----------------------
1 andi mitchel
2 sarah bench
3 kirsty larx
table voucher:
id_v* id_user id_target
1 1 2
2 2 3
quite confused how to join those table with two foreign keys
$db->query("SELECT * FROM voucher v
LEFT JOIN user u ON u.id_u = v.id_user
LEFT JOIN user u1 ON u1.id_u = v.id_target
WHERE .... ")
echoing while loop... and returns nothing??
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
echo $r['u.f_name'];
echo $r['u1.f_name'];
endwhile;
Your JOIN seems absolutely correct. The only issue is that you have joined table user twice, therefore you have columns with same name (like f_name). The database will assign different (but arbitrary) names to these columns. You can override this behaviour with the AS keyword:
$db->query("SELECT v.*
, u.f_name AS user_f_name
, u.l_name AS user_l_name
, ta.f_name AS target_f_name
, ta.l_name AS target_l_name
FROM voucher v
LEFT JOIN user u ON u.id_u = v.id_user
LEFT JOIN user ta ON ta.id_u = v.id_target
WHERE .... ")
Then:
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
echo $r['user_f_name'];
echo $r['target_f_name'];
endwhile;
And I think you can replace the LEFT JOINs with (inner) JOINs. Unless you have id_user or id_target values referencing non-existing userids (id_u).
It looks like you are asking for all people who are in the voucher table regardless of them being in position 1 (user) or position 2 (target)... Then, showing that person's name.
This query does a pre-query of each possible person and their position basis (via WhichPosition).
SELECT STRAIGHT_JOIN
AllVoucherUsers.WhatPosition,
u.*
FROM
( select distinct
v.id_user,
'1' as WhatPosition
from voucher v
union select distinct
v.id_target as id_user,
'2' as WhatPosition
from voucher v
) AllVoucherUsers
join users u
on AllVoucherUsres.id_user = u.id_u
If you only want ONE instance of a given person -- REGARDLESS of their position, just strip out all instances of the "WhatPosition" reference...
SELECT STRAIGHT_JOIN
u.*
FROM
( select distinct
v.id_user
from voucher v
union select distinct
v.id_target as id_user
from voucher v
) AllVoucherUsers
join users u
on AllVoucherUsres.id_user = u.id_u
SELECT * FROM voucher v
LEFT JOIN user u ON u.id_u = v.id_user OR u.id_u = v.id_target
WHERE ....
how about:
SELECT * FROM voucher JOIN user ON id_user = id_u
Simpler still:
SELECT * FROM voucher, user WHERE id_user = id_u

Categories