I have four tables that I need to join together, with one of those tables having two different records I need to grab. The guild and party tables I'm getting the name of those so that I can display the name instead of ID to the user, and the charlog table has the char_id's creation date and last login date that I want to show as well. Here are the tables:
char table:
----------------------------------------------------
| char_id | name | guild_id | party_id |
|---------------------------------------------------
| 150000 | char1 | 3 | 3 |
| 150001 | char2 | 2 | (NULL) |
| 150002 | char3 | (NULL) | 1 |
| 150003 | char4 | 1 | 2 |
----------------------------------------------------
guild table:
-------------------------
| guild_id | name |
-------------------------
| 1 | guild_1 |
| 2 | guild_2 |
| 3 | guild_3 |
-------------------------
party table:
-------------------------
| party_id | name |
-------------------------
| 1 | party_1 |
| 2 | party_2 |
| 3 | party_3 |
-------------------------
charlog table:
----------------------------------------------------
| time | char_id | char_msg |
----------------------------------------------------
| 2015-02-14 06:45:32 | 150000 | make new char |
| 2015-02-14 06:45:58 | 150000 | char select |
| 2015-02-15 12:32:19 | 150001 | make new char |
| 2015-02-15 16:54:01 | 150000 | char select |
| 2015-02-15 19:23:54 | 150001 | char select |
| 2015-02-16 01:32:13 | 150002 | make new char |
| 2015-02-16 01:33:01 | 150003 | make new char |
| 2015-02-16 04:45:43 | 150000 | char select |
| 2015-02-16 07:43:22 | 150003 | char select |
----------------------------------------------------
As mentioned, I need to get the make new char entry from the charlog table to display when the character was created and as well the LAST (by date) char select entry to display when the character was played, all of this with one single char_id.
All in all, I'd be looking for a table that looks like this:
---------------------------------------------------------------------------------------------------------------------
| char_id | name | guild_id | guild_name | party_id | party_name | create_time | lastlogin_time |
---------------------------------------------------------------------------------------------------------------------
| 150000 | char1 | 3 | guild_3 | 3 | party_3 | 2015-02-14 06:45:32 | 2015-02-16 04:45:43 |
I'm using the following active record lines in Codeigniter to attempt to get the data I need. It returns the create_date correctly but the lastlogin_time is not returned (it's blank):
function get_char_info($cid) {
$this->db->select('char.*,guild.guild_id,guild.name AS guild_name,party.party_id,party.name AS party_name,charlog1.time AS create_time,charlog2.time AS lastlogin_time');
$this->db->from('char');
$this->db->where('char.char_id', $cid);
$this->db->join('guild', 'char.guild_id = guild.guild_id', 'left');
$this->db->join('party', 'char.party_id = party.party_id', 'left');
$this->db->join('charlog AS charlog1', 'char.char_id = charlog1.char_id AND charlog1.char_msg = "make new char"', 'left');
$this->db->join('charlog AS charlog2', 'char.char_id = charlog2.char_id AND charlog2.char_msg = (SELECT max(charlog.time) FROM charlog WHERE char_msg = "char select")', 'left');
$query = $this->db->get();
return $query->row();
}
As mentioned, the guild_name, party_name and create_time come through correctly, but the lastlogin_time is blank, no error.
I've tried jumbling some things around in the active record clauses but can't get the lastlogin_time to show. Any help would be appreciated.
The join on your subquery is not correct :
It should be charlog2.time = (SELECT....) not charlog2.char_msg = (SELECT....)
Related
I have the following MySQL table which is structured like that:
| id | bonus0 |
Now I want to add the following data set:
| id | bonus0 | bonus1 | bonus2 | bonus3 |
| 10 | 4582 | 2552 | 8945 | 7564 |
As you can see the columns bonus1 - bonus3 aren´t created yet.
How would a php script/ query look like which checks if enough columns are already available and if not which will create the missing ones with consecutive numbers at the end of the word "bonus"?
So in the example the columns bonus1 - bonus3 would be created automatically by the script.
In reality (I mean a normalized relational database) you should have 3 tables. Lets call them people, bonuses and bonus_to_person
people looks like:
+-----------------+------------+
| person_id | name |
+_________________+____________+
| 1 | john |
+-----------------+------------+
| 2 | frank |
+-----------------+------------+
bonuses Looks like
+----------------+--------------+
| bonus_id | amount |
+________________+______________+
| 1 | 1000 |
+----------------+--------------+
| 2 | 1150 |
+----------------+--------------+
| 3 | 1200 |
+----------------+--------------+
| 4 | 900 |
+----------------+--------------+
| 5 | 150 |
+----------------+--------------+
| 6 | 200 |
+----------------+--------------+
bonus_to_person Looks like
+----------------+-----------------+
| bonus_id | person_id |
+________________+_________________+
| 1 | 1 |
+----------------+-----------------+
| 2 | 2 |
+----------------+-----------------+
| 3 | 2 |
+----------------+-----------------+
| 4 | 1 |
+----------------+-----------------+
| 5 | 1 |
+----------------+-----------------+
| 6 | 1 |
+----------------+-----------------+
This way, any ONE person can have unlimited bonuses simply by INSERTING into bonuses with the amount, and INSERTING into bonus_to_person with the bonus_id and person_id
The retrieval of this data would look like
SELECT a.name, c.amount from people a
LEFT JOIN bonus_to_people b
ON a.person_id = b.person_id
LEFT JOIN bonuses c
ON c.bonus_id = b.bonus_id
WHERE a.person.id = 1;
Your result from something like this would look like
+------------+----+-------+
| name | amount |
+____________+____________+
| john | 1000 |
+------------+------------+
| john | 900 |
+------------+------------+
| john | 150 |
+------------+------------+
| john | 200 |
+------------+------------+
You should be using this normalized approach for any database that will continue growing -- Growing "deeper" than "wider" is better in your case ..
// Get existing columns of the table
// $queryResult = run SQL query using PDO/mysqli/your favorite thing: SHOW COLUMNS FROM `table`
// Specify wanted columns
$search = ['bonus0', 'bonus1', 'bonus2', 'bonus3'];
// Get just the field names from the resultset
$fields = array_column($queryResult, 'Field');
// Find what's missing
$missing = array_diff($search, $fields);
// Add missing columns to the table
foreach ($missing as $field) {
// Run SQL query: ALTER TABLE `table` ADD COLUMN $field INT
}
How can I sort by reference count?
In the above picture,
2-1
1-1
I want to go out like this.
I'm sorry for my bad english
To sort a result set by a column you would append an ORDER clause to your query.
For example:
mysql> SELECT name, birth FROM pet ORDER BY birth;
+----------+------------+
| name | birth |
+----------+------------+
| Buffy | 1989-05-13 |
| Bowser | 1989-08-31 |
| Fang | 1990-08-27 |
| Fluffy | 1993-02-04 |
| Claws | 1994-03-17 |
| Slim | 1996-04-29 |
| Whistler | 1997-12-09 |
| Chirpy | 1998-09-11 |
| Puffball | 1999-03-30 |
+----------+------------+
More information can be found in the manual:
https://dev.mysql.com/doc/refman/5.7/en/sorting-rows.html
I wrote this sql query and it works but it is taking long time to be executed
SELECT trans_files.id, trans_files.game_name, trans_files.file_name,
COUNT(en_txt.id) as txt_num, COUNT(ar_txt.id) as n_txt_num
FROM trans_files
LEFT JOIN en_txt ON en_txt.file_id = trans_files.id
LEFT JOIN ar_txt ON ar_txt.en_text_id = en_txt.id
&& ar_txt.date = (SELECT MAX(ar_txt.date)
FROM ar_txt
WHERE en_text_id = en_txt.id)
GROUP BY trans_files.id
ORDER BY trans_files.id DESC, trans_files.game_name ASC, trans_files.file_name ASC
..
mysql> select * from ar_txt limit 3;
+----+------------+---------+----------------+---------------------+
| id | en_text_id | user_id | text | date |
+----+------------+---------+----------------+---------------------+
| 1 | 16 | 3 | Ϻ┘äÏ▓Ï╣┘è┘à | 2017-01-24 19:10:19 |
| 2 | 18 | 3 | Ϻ┘äϡϻϺϻ | 2017-01-24 19:13:36 |
| 3 | 3 | 3 | Ϻ┘äÏÀÏ¿┘èÏ¿┘è | 2017-01-24 19:15:48 |
+----+------------+---------+----------------+---------------------+
mysql> select * from en_txt limit 3;
+----+---------+------------------+
| id | file_id | text |
+----+---------+------------------+
| 1 | 2 | Apothecary Cheng |
| 2 | 2 | Blacksmith Ho Li |
| 3 | 2 | Apothecary Sung |
+----+---------+------------------+
mysql> select * from trans_files limit 3;
+----+-----------+-----------+
| id | game_name | file_name |
+----+-----------+-----------+
| 1 | drb | skills |
| 2 | drb | npcs |
| 3 | drb | test |
+----+-----------+-----------+
in this case i am using PDO and query to execute it
PHP code
so why does it take a long time?
I have 2 tables, the 'department' and 'document'.
Table department
| doc_id | dept_name |
----------------------------------
| 1 | Information Technology|
| 2 | Software Development |
| 3 | Human Resource |
| 4 | Accounting |
| 5 | Support |
Table document
| doc_id | doc_name | author | description | department |
----------------------------------------------------------------------------
| 1 | Maps | User1 | sample | Information Technology |
| 2 | Audits | User3 | sample | Software Development |
| 3 | Image | User1 | sample | Information Technology |
| 4 | Papers | User4 | sample | Human Resource |
| 5 | Print Screen| User1 | sample | Software Development |
| 6 | Transaction | User3 | sample | Accounting |
| 7 | Graph | User1 | sample | Support |
| 8 | Excel | User1 | sample | Information Technology |
Now, I want to display the table with two columns: department and total_doc.
Output:
| department |total_doc|
-----------------------------------
| Information Technology| 3 |
| Software Development | 2 |
| Human Resource | 1 |
| Accounting | 1 |
| Support | 1 |
I want to display the total document inside the department and arrange them in ascending order.
Here's my query.(not sure)
SELECT department, count(doc_name) as 'total_doc' FROM tbl_document GROUP BY doc_name
I'm using MVC pattern in Codeigniter.
$this->db->select("department, count(doc_name) as 'total_doc'");
$this->db->from('document');
$this->db->group_by('doc_name');
Also, How can I display this in table? like using foreach in html?
You need to do group by with department not with doc_name.
$this->db->select("department, count(doc_name) as 'total_doc'");
$this->db->from('document');
$this->db->group_by('department');
$result = $this->db->get()->result();
Hope This will help you.
foreach ($result as $row)
{
echo $row->department."----".$row->total_doc;
}
here you go
SELECT dept_name,COUNT(td.department) FROM department d
LEFT JOIN tdocument td ON td.`department`=d.`dept_name`
GROUP BY td.`department` ORDER BY COUNT(td.`department`) DESC;
You want one line per department. IN SQL words: You want to group by department.
select department, count(*) as total_doc from document group by department;
(BTW: don't use single quotes for column aliases.)
I have three tables: years, employees, positions. Suppose that I already have these data in those tables.
years:
----------------
| id | name |
----------------
| 1 | 2011 |
----------------
positions:
------------------------------
| id | name | year_id |
------------------------------
| 1 | Director | 1 |
| 2 | Manager | 1 |
------------------------------
employees:
---------------------------------------------------------
| id | name | position_id | year_id |
---------------------------------------------------------
| 1 | Employee A (Director) | 1 | 1 |
| 2 | Employee B (Manager) | 2 | 1 |
---------------------------------------------------------
========================================
The years table is a central point.
If I insert a new year record, I must also copy all positions and employees which are related to the previous year.
So if I insert year 2012 into the years table, the data is suppose to be like this:
years:
----------------
| id | name |
----------------
| 1 | 2011 |
| 2 | 2012 |
----------------
positions:
------------------------------
| id | name | year_id |
------------------------------
| 1 | Director | 1 |
| 2 | Manager | 1 |
| 3 | Director | 2 |
| 4 | Manager | 2 |
------------------------------
employees:
---------------------------------------------------------
| id | name | position_id | year_id |
---------------------------------------------------------
| 1 | Employee A (Director) | 1 | 1 |
| 2 | Employee B (Manager) | 2 | 1 |
| 3 | Employee A (Director) | 3 (?) | 2 |
| 4 | Employee B (Manager) | 4 (?) | 2 |
---------------------------------------------------------
NOTICE the question marks in the third and fourth row of employees table.
I use these queries to insert a new year and copy all related positions and employees:
// Insert new year record
INSERT INTO years (name) VALUES (2012);
// Get last inserted year ID
$inserted_year_id = .......... // skipped
// Copy positions
INSERT INTO positions (name, year_id) SELECT name, $inserted_year_id AS last_year_id FROM positions WHERE year_id = 1;
// Copy employees
INSERT INTO employees (name, position_id, year_id) SELECT name, position_id, $inserted_year_id AS last_year_id FROM employees WHERE year_id = 1;
The problem is at copying employees query. I can't find a method to get or track the new ID of positions.
Is there a simple method to do this?
Thank you very much.
Your data model is seriously flawed and probably needs a complete overhaul, but if you insist on copying the data like you describe, this should do the trick:
// Copy employees
INSERT INTO employees (name, position_id, year_id)
SELECT name, new_positions.id, $inserted_year_id AS last_year_id
FROM employees
JOIN positions AS old_positions ON old_positions.id = employees.position_id
AND old_positions.year_id = employees.year_id
JOIN positions AS new_positions ON new_positions.name = old_positions.name
AND new_positions.year_id = $inserted_year_id
WHERE employees.year_id = 1
I think you should read about database normalization. Copying the data leads to maintenance issues and erroneous reporting.
If you went with a different design like the following, then there would be nothing to insert, until an employee changes position, is terminated, or a position is discontinued. There are plenty of other ways to approach this, too, but you should minimize redundancy (i.e. have only one copy of each Employee), and then keep track of data that changes over time, separately. Also read about foreign keys before you try to implement something like this.
positions:
-- If you are keeping track of the years that each position is active,
-- using dates provides simplicity. Note: this design assumes that positions
-- are never reactivated after being deactivated.
------------------------------------------------
| id | name | DateActive | DateInactive |
------------------------------------------------
| 1 | Director | 01/01/2011 | |
| 2 | Manager | 01/01/2011 | |
------------------------------------------------
employees:
---------------------------------------------------------------
| id | name | DateHired | DateTerminated |
---------------------------------------------------------------
| 1 | Employee A | 01/01/2011 | |
| 2 | Employee B | 01/01/2011 | |
| 3 | Employee C | 01/01/2011 | 10/01/2012 |
---------------------------------------------------------------
EmployeePositionRelationships
--If you are keeping track of time that each employee held a position
-- Employee A has been a Director since 1/1/2011
-- Employee B was a Manager from 1/1/2011 to 10/6/2012. Then they became a Director
-- Employee B was a Manager from 1/1/2011 to 10/1/2012. Then they were terminated
--------------------------------------------------------
EmployeeId | PositionId | DateStarted | DateEnded |
--------------------------------------------------------
1 | 1 | 01/01/2011 | |
2 | 2 | 01/01/2011 | 10/6/2012 |
3 | 2 | 01/01/2011 | 10/1/2012 |
2 | 1 | 10/6/2012 | |
--------------------------------------------------------