Retrieve Value From Database & Replace With Text - php

I am currently performing this statement:
SELECT * FROM b_tasks WHERE CREATED_DATE BETWEEN '$from' AND '$to' AND GROUP_ID=13 ORDER BY ID DESC
This returns:
Responsible ID | Title | Date Created
2 | Job 1 | 2013/09/20
4 | Job 2 | 2013/09/20
The responsible_id represents an actual name in number form. For example resonsible_id 2 is actually Bob Taylor and responsible_id 4 is Andrew Thompson. So what I'd like to do is replace the numbers in the table with their name, so where its 2, display Bob Taylor and where its 4 display Andrew Thompson.
I am currently printing these answers using PHP.
. $row['RESPONSIBLE_ID'] .
Should I be using an IF statement, if responsible_id=2 display Bob and so on?
Any ideas?
UPDATE:
There is a User Table yes, this reads:
Table name: b_users
ID | NAME | LAST_NAME
1 | Andy | Champ
2 | Bob | Taylor
3 | Katie | Gillo
4 | Andrew | Thompson
Obviously, ID in this table corresponds with responsible_id in the other table. Would I be able to join these in the same statement above?

do you have a table that you can join to? if not, you can use CASE
CASE WHEN Responsible_ID = 2 THEN 'Bob Taylor'
WHEN Responsible_ID = 4 THEN 'Andrew Thompson'
ELSE Responsible_ID
END AS Responsible_ID
SELECT a.*,
CONCAT(b.Name, ' ', b.Last_Name) Fullname
FROM b_tasks a
INNER JOIN b_users b
ON a.Responsible_ID = b.ID
WHERE CREATED_DATE BETWEEN '$from' AND '$to' AND GROUP_ID=13
ORDER BY ID DESC
and call $row['Fullname']

try this
UPDATE `table` SET `id` = CASE
WHEN id = 1 THEN 'value1'
WHEN id = 2 THEN 'value2'
WHEN id = 3 THEN 'value3'
ELSE `id`
END
WHERE id in (1,2,3)

Related

How do I get distinct rows by a column?

I have a huge number of rows that I'd like to get say, last 5 records inserted in that database from 10 different users. If the same user inserted the last 3 rows into database, we must get one row, skip the others two and move to get a row per user, until it count up to 5.
A database like that:
user_id | news_id | title
1 | 1 | foo-1
2 | 2 | foo-2
3 | 3 | foo-3
1 | 4 | baa
4 | 5 | baa0
5 | 6 | baa1
5 | 7 | baa2
6 | 8 | baa3
7 | 9 | baa4
Should return:
user_id | news_id | title
1 | 1 | foo-1
2 | 2 | foo-2
3 | 3 | foo-3
4 | 5 | baa0
5 | 6 | baa1
The current filter was done by PHP, like this:
$used = array();
while ($data = mysql_fetch_array($query)) {
$uid = $data['user_id'];
if(in_array($uid, $used))
continue;
array_push($used, $uid);
// do something with data
}
But I want to refactor it, and do the filter purely by mysql, if possible. I don't know much MySql and that's why I'm having problem to archive this...
Here's what I've tried
select DISTINCT(user_id), news_id, title from XXX
WHERE GROUP BY (news_id) DESC
LIMIT 0,5
How can I do that?
1 way you can do it is to generate a partitioned row number per user and then select 5 records where RowNumber = 1.
SELECT *
FROM
(
SELECT
d.user_id
,d.news_id
,d.title
,(#rn:= if(#uid = user_id, #rn + 1,
if(#uid:=user_id,1,1)
)
) as RowNumber
FROM
Data d
CROSS JOIN (SELECT #uid:=-1, #rn:=0) vars
ORDER BY
user_id
,news_id
) t
WHERE
t.RowNumber = 1
ORDER BY news_id
LIMIT 5;
http://rextester.com/JRIZI7402 - example to show it working
Note you can change the row order by simply changing the ORDER BY statement of the derived table so if you have a column that will signify the latest record e.g. an identity column or a datetime column you can use that, but user_id must be the first criteria to be partitioned correctly.
Do it from your query.
"SELECT * FROM table GROUP BY user_id ORDER BY news_id DESC LIMIT 5"
well, i think this will achieve what you are after.
select user_id, news_id, title from tableName
GROUP BY user_id
ORDER BY news_id DESC
LIMIT 0,5
Hope this helps!

Double SQL Query - JOIN

I need a double SELECT sql query from 2 different tables with names visits & items
1.: SELECT visitid, visitdate, visitreason FROM visits WHERE personid = 10
2.: SELECT itemid, itemname, itemtime FROM items WHERE itemvisitid= visitid
I think I need to do a JOIN but don’t know exactly how.
Table examples:
Table: visits
visitid | personid | visitdate | visitreason
1 | 10 | 05/07/2014 | no reason
2 | 10 | 06/07/2014 | some reason
3 | 12 | 06/07/2014 | no reason
4 | 10 | 12/07/2014 | some other reason
Table: items
itemid | personid | itemvisitid | itemname | itemtime
1 | 10 | 2 | box | 23
2 | 10 | 2 | clock | 70
3 | 10 | null | water | 50
4 | 10 | null | paper | 40
5 | 12 | 3 | box | 26
What I have now is this:
$query = "SELECT visitid, visitdate, visitreason FROM visits WHERE personid = '10' ORDER BY visitdate DESC";
// 2nd select: "SELECT itemid, itemname, itemtime FROM items WHERE itemvisitid= visitid";
$db->setQuery($query);
$results = $db->query();
while($row = mysqli_fetch_array($results)){
echo "<tr>
<td>".$row['visitid'].", ".$row['visitdate']."</td>
<td>".$row['visitreason']."</td>
<td>".$row['itemid'].",".$row['itemname'].", ".$row['itemtime']."</td>
</tr>";
}
I need results to be something like this:
<tr>
<td>1, 05/07/2014</td><td>no reason</td><td></td>
<td>2, 06/07/2014</td><td>some reason</td><td>1, box, 23<br />2, clock, 70</td>
<td>4, 12/07/2014</td><td>some other reason</td><td></td>
</tr>
I guess your might to use GROUP_CONCAT like this:
DEMO: http://sqlfiddle.com/#!2/9d4e22/15
SELECT visitid, DATE_FORMAT(visitdate,'%m/%d/%Y'), visitreason,
GROUP_CONCAT(itemid,itemname, itemtime)
FROM visits left join items on visits.visitid = items.itemvisitid
WHERE visits.personid = 10
GROUP BY visitid, visitdate, visitreason
You might want to read this to know GROUP_CONCAT :
How to use GROUP_CONCAT in a CONCAT in MySQL
The document of GROUP_CONCAT() is here:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
hope this helps.
SELECT `visits`.`visitid`, `visits`.`visitdate`, `visits`.`visitreason`,`items`.`itemname`, `items`.`itemtime` from `visits` INNER JOIN `items` ON `visits`.`personid`=`items`.`personid` WHERE `visits`.`personid` = '10' ORDER BY `visits`.`visitdate` DESC
if there is any error please change the field name personid in 'items' table.and then check.
This query:
SELECT v.visitid,
v.visitdate,
v.visitreason,
i.itemid,
i.itemname,
i.itemtime
FROM visits v
INNER JOIN items i
ON ( v.visitid = i.itemvisitid )
WHERE v.person_id = 10
ORDER BY v.visitdate DESC,
i.itemid ASC
will link both tables and produce a resultset that you can traverse using a double loop. The outer loop to process changes to the visit, and the inner to add every item visited in a particular visit.

SQL Count most used value in one column where other column equals something.

This is a bit of a weird one I didn't know how to word the title please bear with me.
So I have a table like this which stores data on different jobs:
id | company | contact
----------------------
0 | name1 | Bob
1 | name1 | Mark
2 | name3 | Sam
3 | name1 | Bob
4 | name2 | Nigel
5 | name1 | Bob
6 | name3 | Donald
7 | name1 | Sandy
8 | name3 | Nigel
Is there a query with SQL I can use to query the table to find out the most commonly used contact for a particular company.
So the theoretical code I would be looking for would be something like:
SELECT "Most Commonly used Contact" FROM table WHERE company = "$company";
Is it possible in a single query or is this a multi query job?
try this sql query...
SELECT *, COUNT(*) AS total
FROM table
WHERE company = '$company'
GROUP BY contact
ORDER BY total DESC
LIMIT 1
Basically you want to find the number of contacts grouped by each company, and then grouped by the actual contact. So in other words:
SELECT COUNT(`id`) as num_contacts, `contact`, `company` FROM `jobtable` GROUP BY `company`, `contact` ORDER BY `company`, num_contacts DESC
Or for a single company:
SELECT COUNT(`id`) as num_contacts, `contact` FROM `jobtable` WHERE `company`='$company' GROUP BY `contact` ORDER BY num_contacts DESC
Gives you the single most used contact for $company, if you can't use LIMIT (e.g. if you are utilizing an Oracle Database):
SELECT contact, used_by
FROM (
SELECT contact, COUNT(*) AS used_by
FROM table
WHERE company = $company
GROUP BY contact
) t
HAVING used_by = MAX(used_by)

SQL query to select only the maximum items?

I have this table: I want to search by UID
ID | VID | UID
1 | 1 | 5
1 | 1 | 6
1 | 2 | 6
2 | 3 | 5
2 | 3 | 6
2 | 4 | 6
I want to end up with this result:
ID | VID | UID
1 | 2 | 6
2 | 4 | 6
In other words, only select the entries where the VID is MAX of the UID but keeping in min NID could differ. Something like this I suppose:
select * from TABLE where uid = 6 and max(vid)
???
But this doesn't work?
One way is to order by the value in descending order (so the max is at the top), then just select the first result.
SELECT t.ID,
t.VID,
t.UID
FROM table t
WHERE t.ID = 1
ORDER BY t.VID DESC
LIMIT 1
Or do you mean you want all rows where t.VID is the highest value? In which case you could do something like this,
SELECT t.ID,
t.VID,
t.UID
FROM table t
WHERE t.ID = 1
AND t.VID = (SELECT MAX(VID) FROM table);
EDIT: Based on the edit to your question, it looks like you just want the max VID value for each ID? If I'm understanding you correctly, then this should give you what you need.
SELECT t.ID,
max(t.VID) as VID,
t.UID
FROM table t
WHERE t.UID = 6
GROUP BY t.ID
You need to have a subquery. This should work:
select * from TABLE where ID='1' AND VID=(select max(VID) from TABLE)
I expect your real-life example is more complicated (at least has more data).
This query will give you the row you want.
SELECT id,vid, uid
FROM TABLE
where id = 1
and vid in (select max(vid) from TABLE where id = 1)

SQL: GROUP BY records and then get last record from each group? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SQL Server: Only last entry in GROUP BY
I have a table like this:
id| name | attendence
1 | Naveed| 1
2 | Naveed| 1
3 | Adil | 1
4 | Adil | 1
I use following query:
SELECT * FROM `test` WHERE `attendence`=1 GROUP BY name
The result with above query:
id| name | attendence
3 | Adil | 1
1 | Naveed | 1
Question:
Above result group rows by name but show first row from each group. I want to select last row(by id) from each group.
For example:
id| name | attendence
2 | Naveed | 1
4 | Adil | 1
How to write query for above result.
Thanks
SELECT a.*
FROM test a
WHERE a.attendence = 1
AND NOT EXISTS (select 1 from test where name = a.name and id > a.id and attendence = 1)
GROUP BY name
Might not even need the group by anymore.
SELECT MAX("id"), "name" FROM "test" WHERE "attendence" = 1 GROUP BY "name"
SELECT Name, Max(ID) FROM table WHERE attendance = 1 GROUP BY Name
Use the following query:
SELECT * FROM `test` WHERE `attendence`=1 GROUP BY name ORDER BY `id` DESC LIMIT 1
That will only select the row that meets the criteria with the highest id.

Categories