mysql(i): Selecting data from multiple tables? - php

Say if I have 2 tables. The first one holds users ids and their first names. The second one holds user ids and their last names, but the rows in this table may or may not exist depending on whether the user has given their last name or not.
I want to select both the first name and the last name, but if only the first name exists then to just select that on its own.
I cant use something like this because if the second table row doesn't exist then it returns nothing:
$db->query("select firstname.fname, lastname.lname from firstname, lastname where firstname.userid = lastname.userid");
Thanks.

SELECT f.fname, l.lname
FROM firstname f
LEFT JOIN lastname l
ON f.userid = l.userid
this will return something like:
fname | lname
John | Doe
Bob | NULL
where NULL means that Bob hasn't got a last name
JOIN is more performant than cartesian product you are using in your example because it won't produce all the possible combinations of {firstame,lastname} but just the ones which make sense (the ones with the same userid)

Related

How can I count a specific value in a mysql table and echo with php, how many times the varchar is in the table?

I have a MySQL table with several varchars in a column. Now I want to count how many times specific varchar is in this column. Then I want to echo the number that was counted. Can someone tell me what SQL Code I have to use and how I can convert the SQL result to an integer in PHP?
My table:
Let's suppose you have a table with customers data called CUSTOMERS, one of its columns being "NAME".
You could do something like this:
SELECT NAME, COUNT(NAME) AS TOTAL FROM CUSTOMERS GROUP BY NAME
So you will get something like this:
NAME | TOTAL
-----+------
John | 5
Mary | 3
Bort | 9999
If you want to filter by a specific name, you could do something like this:
SELECT NAME, COUNT(NAME) AS TOTAL FROM CUSTOMERS WHERE NAME = 'John' GROUP BY NAME
NAME | TOTAL
-----+------
John | 5
For the second part, it would depend how are you accessing data from your database. For example if you are iterating every row using mysql_fetch_array, and saving the row in a variable $row, you only need to do this:
$name = $row['NAME'];
$total = $row['TOTAL'];

update column based on two columns

I have a weird problem.
I have a rather large database with two tables. I need to change a column's contents from a name to an ID that already exists in another table.
Example:
I have a table that contains a column "Name"
the name column has the persons "lastname, firstname" as shown
Name | othercolumn
Smith, John |
I would like to change the contents of the name column to the staffID associated with the persons name.
The staff table is
staffID | firstName | lastName
1 john smith
My end result should be
Name | othercolumn
1 |
I've tried all sorts of joins and concats, but can't seem to get it down with my limited mysql knowledge. Is there a way to do this without having to do it manually? The comma seems to give me alot of grief. Thanks!
You need to be very careful about this. First, I assume that StaffId is a number. So, add a column to the table:
alter table t add StaffId int;
Then, update this column:
update t join
staff s
on t.name = concat_ws(',', s.lastname, s.firstname)
set t.StaffId = s.StaffId;
Note that after you have done this, you may still have StaffId values that are NULL:
select t.*
from t
where t.StaffId is null;
These are the names that are not in the staff table. They require more work. When you are done, you can drop the name column.

SQL finding specific character in table

I have a table like this
d_id | d_name | d_desc | sid
1 |flu | .... |4,13,19
Where sid is VARCHAR. What i want to do is when enter 4 or 13 or 19, it will display flu. However my query only works when user select all those value. Here is my query
SELECT * FROM diseases where sid LIKE '%sid1++%'
From above query, I work with PHP and use for loop to put the sid value inside LIKE value. So there I just put sid++ to keep it simple. My query only works when all of the value is present. If let say user select 4 and 19 which will be '%4,19%' then it display nothing. Thanks all.
If you must do what you ask for, you can try to use FIND_IN_SET().
SELECT d_id, d_name, d_description
FROM diseases
WHERE FIND_IN_SET(13,sid)<>0
But this query will not be sargable, so it will be outrageously slow if your table contains more than a few dozen rows. And the ICD10 list of disease codes contains almost 92,000 rows. You don't want your patient to die or get well before you finish looking up her disease. :-)
So, you should create a separate table. Let's call it diseases_sid.
It will contain two columns. For your example the contents will be
d_id sid
1 4
1 13
1 19
If you want to find a row from your diseases table by sid, do this.
SELECT d.d_id, d.d_name, d.d_description
FROM diseases d
JOIN diseases_sid ds ON d.d_id = ds.d_id
WHERE ds.sid = 13
That's what my colleagues are talking about in the comments when they mention normalization.

how to get user name based on id separated by comma in single table

user_id user_name user_friend_list
1 dharmendra 2,3,4,5,6,7
2 jitendra 1,3,4,5,6,7
3 xyz 1,2,6,7
4 pqr 1,3,4
now i want to extract user_id & user name based on user_friend_list id 6 i.e
it will return 1,2,3 user_id & user name dharmendra jitendra and xyz.
i simply use splite function of php but it is so complicated please provide me well shortcut method
thanks & regards
You can use FIND_IN_SET()
select user_id, user_name
from your_table
where find_in_set(6, user_friend_list) > 0
But it would actually be better to change your table design. Never store multiple values in one column!
first thing the table is not normalized that's why the problem exist
you must break this table like this or better :)
table 1
user_id
user_name
table 2
user_id
friend_id
table 2 will have some redundant data though which can be removed by adding a third table as a mapping between table1 and table2
now you can have the following query to get the result
select user_id,user_name from table1 as a join table2 as b on a.user_id=b.user_id where b.friend_id=6;
"SELECT user_id,username from your table WHERE user_id IN (2,3,4,5,6,7)";

SQL: Select based on related_id and related_table. ID's stored in array named for table

I have a table called activities that looks like this
id | related_id | related_table | ...
And 3 arrays, each named after a table, containing ID's:
$clubs[1,2,3]; $vendors[4,5,6]; $users[7,8,9];
How do I select the activities that belong to the corresponding clubs, vendors, and users in the arrays? I only know very simple SQL, but am sure there is a way to do this.
I am looking to do this in 1 select statement, if possible. Otherwise I know how to do "where in" to do it in 3.
ANSWER:
Here is how I accomplished getting all the activites in 1 select:
'SELECT * from activities where (related_table = \'clubs\' and related_id in ('.$clubs_string.')) or (related_table = \'vendors\' and related_id in ('.$vendors_string.')) or (related_table = \'users\' and related_id in ('.$users_string.'));';
See Morgan Wilde's answer about implode()-ing the arrays to strings.
Well if I've got your question right, the way to find all activities that relate to club id's saved in an array should be...
$clubs_string = implode(",", $clubs); // convert your array into a comma separated string
Once you've got that sorted, send a query like
SELECT `id` FROM `activities` WHERE `related_id` IN ({$clubs_string}) AND `related_table` = 'club_table_name'
You can repeat the same logic for all other table types that you have.
Here you can find some neat MySQL WHERE IN examples - http://www.tutorialspoint.com/mysql/mysql-in-clause.htm
Hope that helps!

Categories